{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a93bf0de-ecf1-4711-a721-5f3bf2a044f0",
   "metadata": {
    "vscode": {
     "languageId": "python"
    }
   },
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "from mlxtend.preprocessing import TransactionEncoder\n",
    "from mlxtend.frequent_patterns import apriori, association_rules\n",
    "\n",
    "df = pd.read_excel('./222/餐厅数据.xlsx')\n",
    "#print(df.head)\n",
    "\n",
    "# 转换菜品格式\n",
    "transactions = df['菜品'].str.split(',').to_list()\n",
    "\n",
    "# 标准化\n",
    "te = TransactionEncoder()\n",
    "te_ary = te.fit(transactions).transform(transactions)\n",
    "df_encoded = pd.DataFrame(te_ary, columns=te.columns_)\n",
    "\n",
    "# print(df_encoded.head())\n",
    "# 使用apriori进行分析\n",
    "frequent_itemsets = apriori(df_encoded, min_support=0.1, use_colnames=True)\n",
    "frequent_itemsets.sort_values(by='support', ascending=False, inplace=True)\n",
    "\n",
    "# 选择二项集查看\n",
    "print(frequent_itemsets[frequent_itemsets.itemsets.apply(lambda x: len(x) == 2)])\n",
    "\n",
    "# 生成关联规则\n",
    "rules = association_rules(frequent_itemsets, metric=\"confidence\", min_threshold=0.1)\n",
    "rules = rules.sort_values(by=['lift'], ascending=False)\n",
    "\n",
    "# 保存模型结果\n",
    "frequent_itemsets.to_pickle(\"frequent_itemsets.pkl\")\n",
    "rules.to_pickle(\"rules.pkl\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "",
   "name": ""
  },
  "language_info": {
   "name": ""
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
